var app = new getApp();
Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    ossImg: `${app.globalData.imgUrl}/applet_web_images/new_image`,
    winHeight: 0, // 当前设备的高度
    tabs: [{
        cate_name: '全部订单',
        checked: 'active',
        status: '',
      },
      {
        cate_name: '未完成',
        checked: '',
        status: 99,
      },
      {
        cate_name: '审核中',
        checked: '',
        status: 1,
      },
      {
        cate_name: '待支付',
        checked: '',
        status: 2,
      },
      {
        cate_name: '待发货',
        checked: '',
        status: 3,
      },
      {
        cate_name: '租用中',
        checked: '',
        status: 4,
      },
  
      // {
      //   cate_name: '已完成',
      //   checked: '',
      //   status: 6,
      // },
      {
        cate_name: '逾期中',
        checked: '',
        status: 7,
      },
      {
        cate_name: '续租中',
        checked: '',
        status: 13,
      },
      // {
      //   cate_name: '待取消',
      //   checked: '',
      //   status: 77,
      // },
      // {
      //   cate_name: '订单取消',
      //   checked: '',
      //   status: 8,
      // },
      // {
      //   cate_name: '审核拒绝',
      //   checked: '',
      //   status: 9,
      // },
      // {
      //   cate_name: '已买断',
      //   checked: '',
      //   status: 12,
      // },
      {
        cate_name: '待归还',
        checked: '',
        status: 5,
      },
    ],
    order_data: [],
    loadData: {
      // 加载更多
      page: 1, // 页码
      pageSize: 4, // 数量
      totalPage: 10,
    },
    showText: false, // 是否显示加载更多的提示
    loadText: '加载中。。。',
    order_status: 0, // 订单状态
    isXuZushow: true, //是否显示续租
    ismoveMenuBtn: false, //popover 显示隐藏
    movegoodid: 0, //点击的商品id
    selectOrder_id: 0, //点击的订单id
    tabscroll_left: 0, //滑动距离
    is_load: false, //是否加载
    addGroupHide: false, // 加群弹窗
    orderStr: '', // 支付宝继续下单必备参数
    isHideToExamineProup: false, // 是否显示催审核弹窗
    isHideDeliveryProup: false, // 是否显示催发货弹窗
    kefuisShow: false,//客服弹框
    isShowRentedAndReturned: false,
    popupRentedAndReturned: {},
    isHidePlaceOrderPopup: false, // 挽留弹窗
    retentionFaceParams: null // 继续下单人脸取消，出现挽留弹窗点击继续所需的参数
  },
  // 关闭群
  closeGroupPopup() {
    this.setData({
      addGroupHide: false
    })
  },

  // 关闭客服弹窗
  closekefu() {
    this.setData({
      kefuisShow: false
    })
  },

  // 加群
  jumpGroup() {
    my.ap.openURL({
      url: 
      'alipays://platformapi/startapp?appId=68687451&url=%2Fwww%2Fbc-join.html%3Foid%3D2023020316330500021149%26businessId%3D2023020316330500021149%26businessType%3D18%26source%3DOTHERS'
    })
  },

  jumpPage({ target: { dataset: {url, order_id, attr_id, goods_id, order_type, relet_order_no}}}) {

    if(order_id || attr_id || goods_id || order_type || relet_order_no) {
      my.navigateTo({
        url: 
        `${url}?order_id=${order_id}&attr_id=${attr_id}&goods_id=${goods_id}&order_type=${order_type}&relet_order_no=${relet_order_no}`
      })
    } else {
      my.navigateTo({
        url
      })
    }
  },

  // 催审核
  urgeMethod({ target: { dataset: {order_id, key, visible}}}) {
    let { data } = my.getStorageSync({ key });
    const result =  data || []
    result.push(order_id)
    my.setStorage({
      key,
      data: result,
      success: () => {
        this.orderList('click')
 
        const { isHideDeliveryProup, isHideToExamineProup } = this.data
        isHideDeliveryProup && this.setData({
          isHideDeliveryProup: false
        })
        isHideToExamineProup && this.setData({
          isHideToExamineProup: false
        })
        this.setData({
          [visible]: true
        })

        setTimeout(() => {
          this.setData({
            [visible]: false
          })
        }, 10000)
      }
    });
  },

  // 点击tab栏
  clickTabs(e) {
    let vm = this;
    let index = e.target.dataset.id;
    let tabsData = vm.data.tabs;

    tabsData.forEach((item, index) => {
      item.checked = '';
    });
    tabsData[index].checked = 'active';

    vm.setData({
      tabsId: index,
      order_status: tabsData[index].status,
      tabs: tabsData,
    });

    vm.setData({
      loadText: '',
      loadData: {
        // 加载更多
        page: 1, // 页码
        pageSize: 4, // 数量
        totalPage: 10,
      },
    });
    vm.orderList('click');
  },
  // 跳转到详情
  toDetail(e) {
    var order_id = e.currentTarget.dataset.orderId;
    // console.log(order_id)
    my.navigateTo({
      url: 'orderdetail/orderdetail?order_id=' + order_id,
    });
  },
  onLoad(options) {

    const { showGroup, platform  } = options
    if(showGroup) {
      this.setData({
        addGroupHide: true
      })
    }

    // 检测是否从其它来源进来的,比如分享渠道
    if(platform) {
      app.globalData.platform = platform
    }

    // 如果是从外链跳转过来的就执行

    if (my.getStorageSync({
        key: 'isOtherApp'
      }).data) {
      app.getUserPhone(() => {
        // app.globalData.user_id = res2.user_id;

        let vm = this;

        let id = options.id === undefined ? '' : parseInt(options.id);
        // 根据上个页面传递过来的id,判断快递进行到了那个阶段
        let tabs = vm.data.tabs;
        tabs.forEach((item, index) => {
          item.checked = '';
          if (item.status === id) {
            item.checked = 'active';
            vm.setData({
              tabsId: index,
              order_status: id,
            });
          }
        });
        vm.setData({
          tabs: tabs,
        });
        my.createSelectorQuery()
          .select('.scroll-view_H .active')
          .boundingClientRect()
          .exec((ret) => {
            if (ret[0]) {
              vm.setData({
                tabscroll_left: ret[0].left,
              });
            }
          });
        if (app.globalData.user_id != '') {
          this.setData({
            loadText: '',
            loadData: {
              // 加载更多
              page: 1, // 页码
              pageSize: 4, // 数量
              totalPage: 10,
            },
          });

          vm.orderList('click');
        } else {
          app.getAuth_base(function (userid) {
            this.setData({
              loadText: '',
              loadData: {
                // 加载更多
                page: 1, // 页码
                pageSize: 4, // 数量
                totalPage: 10,
              },
            });
            vm.orderList('click');
          });
        }
      });
      my.removeStorageSync({
        key: 'isOtherApp',
      });

      return;
    }

    let vm = this;

    let id = options.id === undefined ? '' : parseInt(options.id);
    // 根据上个页面传递过来的id,判断快递进行到了那个阶段
    let tabs = vm.data.tabs;
    tabs.forEach((item, index) => {
      item.checked = '';
      if (item.status === id) {
        item.checked = 'active';
        vm.setData({
          tabsId: index,
          order_status: id,
        });
      }
    });
    vm.setData({
      tabs: tabs,
    });
    my.createSelectorQuery()
      .select('.scroll-view_H .active')
      .boundingClientRect()
      .exec((ret) => {
        if (ret[0]) {
          vm.setData({
            tabscroll_left: ret[0].left,
          });
        }
      });
    if (app.globalData.user_id != '') {
      this.setData({
        loadText: '',
        loadData: {
          // 加载更多
          page: 1, // 页码
          pageSize: 4, // 数量
          totalPage: 10,
        },
      });

      vm.orderList('click');
    } else {
      app.getAuth_base(function (userid) {
        this.setData({
          loadText: '',
          loadData: {
            // 加载更多
            page: 1, // 页码
            pageSize: 4, // 数量
            totalPage: 10,
          },
        });
        vm.orderList('click');
      });
    }
  },
  onHide() {
    // 页面隐藏
  },

  onShow() {
    // 页面显示
    let vm = this;

    if (vm.data.isLoad) {
      if (app.globalData.user_id != '') {
        this.setData({
          loadText: '',
          loadData: {
            // 加载更多
            page: 1, // 页码
            pageSize: 4, // 数量
            totalPage: 10,
          },
        });
        vm.orderList('click');
      } else {
        app.getAuth_base(function (userid) {
          this.setData({
            loadText: '',
            loadData: {
              // 加载更多
              page: 1, // 页码
              pageSize: 4, // 数量
              totalPage: 10,
            },
          });
          vm.orderList('click');
        });
      }
    }

    this.setData({
      movegoodid: 0,
      ismoveMenuBtn: false, //点击的商品id
      selectOrder_id: 0, //点击的订单id
    });
  },

  // 请求订单列表的数据
  orderList(type) {
    let app = getApp();
    let vm = this;
    let isLoad = false;
    if (type == 'loading') {
      isLoad = true;
    }
    if (type == 'click') {
      vm.setData({
        order_data: [],
      });
    }
    my.showLoading({
      content: '加载中...',
      delay: 0,
    });

    my.request({
      url: app.globalData.testUrl + '/Api/my/orderList',
      method: 'POST',
      cache: false,
      data: {
        user_id: app.globalData.user_id,
        //user_id: "2088012922006178",
        //phone: 18625988313,//测试
        order_status: vm.data.order_status,
        page: vm.data.loadData.page,
        pageSize: 1000,
      },
      success: (res) => {
        //console.log("订单列表",res);
        if (res.data.status == '1001') {
          my.stopPullDownRefresh(); //关闭下拉刷新
          vm.setData({
            showText: false,
          });
          
          let order_data = vm.data.order_data;
          let { data: isUrgeToExamineOrderList } = my.getStorageSync({ key: 'isUrgeToExamineOrderList' });
          let { data: isDeliveryOrderList } = my.getStorageSync({key: 'isDeliveryOrderList'})
          for (let i = 0; i < res.data.data.data.length; i++) {
            const { data } = res.data.data

            if(Array.isArray(isUrgeToExamineOrderList) && isUrgeToExamineOrderList.includes(data[i].order_id)) {
              data[i].isUrgeToExamine = true
            }

            if(Array.isArray(isDeliveryOrderList) && isDeliveryOrderList.includes(data[i].order_id)) {
              data[i].isDelivery = true
            }

            order_data.push(data[i]);
          }


          
          vm.setData({
            order_data: order_data,
            is_load: true,
          });

          const isRentedAndReturned = res.data.data.data.filter(item => {
            if(item.is_show_change_lease_schemes_btn) {
              return item
            }
          })

          if(isRentedAndReturned.length) {
            const { attr_id, goods_id, order_id } = isRentedAndReturned[0]
            const popupRentedAndReturned = { attr_id, goods_id, order_id }
            this.setData({
              popupRentedAndReturned,
              isShowRentedAndReturned: true
            })
          } else {
            this.setData({
              isShowRentedAndReturned: false,
              popupRentedAndReturned: {}
            })
            
          }


          // if (res.data.data) {
          //   if (vm.data.loadData.page < res.data.data.totalPage) {
          //     vm.setData({
          //       loadData: {
          //         page: vm.data.loadData.page + 1,
          //         pageSize: vm.data.loadData.pageSize,
          //         totalPage: res.data.data.totalPage,
          //       }
          //     })
          //   }
          // }
        }
      },
      complete: function (res) {
        my.hideLoading();
      },
    });
  },

  closePopupRentedAndReturned() {
    this.setData({
      isShowRentedAndReturned: false
    })
  },

  jumpRentedAndReturn() {
    const { 
      attr_id, goods_id, order_id
    } = this.data.popupRentedAndReturned


    my.navigateTo({
      url: `/page/mine/myorders/gift/gift?order_id=${order_id}&attr_id=${attr_id}&goods_id=${goods_id}`
    })
  },

  md(e) {
    //买断
    let order_id = '';
    if (e) {
      order_id = e.currentTarget.dataset.orderId;
    } else {
      order_id = this.data.selectOrder_id;
    }
    my.navigateTo({
      url: '../../rent/buyout/buyout?orderid=' + order_id,
    });
  },
  // 触底加载更多
  onReachBottom() {
    // let vm = this;
    // if (vm.data.loadData.page < vm.data.loadData.totalPage) {
    //   vm.setData({
    //     loadData: {
    //       page: vm.data.loadData.page + 1,
    //       pageSize: vm.data.loadData.pageSize,
    //       totalPage: vm.data.loadData.totalPage
    //     },
    //     showText: true,
    //     loadText: '加载中~',
    //   })
    //   vm.orderList('loading');
    // } else {
    //   this.setData({
    //     showText: true,
    //     loadText: '没有更多了哦',
    //   })
    // }
  },
  //下拉刷新
  onPullDownRefresh() {
    this.setData({
      loadText: '',
      loadData: {
        // 加载更多
        page: 1, // 页码
        pageSize: 4, // 数量
        totalPage: 10,
      },
    });
    this.orderList('click');

    //	this.getProductList("pulldown"); //大家都在买
  },
  itemTap1() {
    console.log('52564675123');
  },
  onReady() {
    this.animation = my.createAnimation({
      duration: 200,
    });
  },
  moveMenu(e) {
    //点击更多按钮
    console.log(e);
    let vm = this;
    let _movegoodid = e.currentTarget.dataset.id;

    vm.setData({
      selectOrder_id: e.currentTarget.dataset.orderId,
    });
    if (!vm.data.ismoveMenuBtn) {
      this.animation.rotate(0).step();
      this.setData({
        animation: this.animation.export()
      });
    } else {
      this.animation.rotate(180).step();
      this.setData({
        animation: this.animation.export()
      });
    }

    if (_movegoodid == vm.data.movegoodid) {
      vm.setData({
        ismoveMenuBtn: !vm.data.ismoveMenuBtn,
      });
    } else {
      this.animation.rotate(0).step();
      this.setData({
        animation: this.animation.export()
      });
      vm.setData({
        ismoveMenuBtn: true,
        movegoodid: _movegoodid,
      });
    }
  },
  onItemXuZu() {
    //续租
    my.navigateTo({
      url: 'renewal/renewal?order_id=' + this.data.selectOrder_id,
    });
  },
  onItemGuiHuan() {
    my.navigateTo({
      url: 'returngoods/returngoods?order_id=' +
        this.data.selectOrder_id +
        '&typeindex=2',
    });
  },
  onItemYiGuiHuan(e) {
    my.navigateTo({
      url: 'returngoods/returngoods?order_id=' +
        e.currentTarget.dataset.orderId +
        '&isGuiHuan=false',
    });
  },

  goExpress(e) {
    my.navigateTo({
      url: 'express/express?order_id=' + e.currentTarget.dataset.orderId,
    });
  },

  // 挽留弹窗继续下单取消
  confirmDeparture() {
    this.setData({
      isHidePlaceOrderPopup: false,
      retentionFaceParams: null
    })
  },

  // 继续下单
  payment(e) {
    //立即付款
    my.showLoading({
      content: '加载中...',
      delay: 0,
    });
    const {
      orderId: order_id, 
      is_face_auth,
      is_skip_face_auth
    } = e.currentTarget.dataset
    const { testUrl, user_id: zm_user_id } = app.globalData
    const retentionFaceParams = {
      order_id,
      is_face_auth,
      is_skip_face_auth
    }
    this.setData({
      retentionFaceParams,
      isHidePlaceOrderPopup: false
    })
    my.request({
      url: `${testUrl}/Api/order/NopayFreeze`,
      method: 'POST',
      cache: false,
      data: {
        order_id,
        zm_user_id,
      },
      success: (res) => {
        if (res.data.status == '1001') {
          const {
            orderStr, // 预授权订单号
            order_id
          } = res.data.data

          let data = {
            order_id, //订单号
            status: 'SUCCESS', //下单状态
            zm_user_id,
          };
          this.setData({
            orderStr
          })
          
          if(is_skip_face_auth) { // 刷单直接预授权不需要人脸
            my.request({
              url: `${testUrl}/api/user/userFaceAuthSuccess`,
              method: 'POST',
              data: {
                order_id
              },
              dataType: 'json',
              success: () => { // 成功和失败都拉起预授权
                
                this.preAuthorization(data)
              },
              fail: () => { 
                this.preAuthorization(data)
              }
            })
            return
          }
          // 若已经人脸识别
          if(is_face_auth) {
            this.preAuthorization(data)
          } else {
            this.authentication(order_id, data)
          }
        } else if(res.data.status === '101') {

          my.confirm({
            title: res.data.msg,
            confirmButtonText: '咨询客服',
            cancelButtonText: '取消',
            success: (result) => {
              const { confirm } = result
              if(confirm) {
                this.setData({
                  kefuisShow: true
                })
              }
            },
          });
        } else {
          my.showToast({
            type: 'fail',
            content: res.data.msg,
            duration: 2000,
          });
        }
      },
      complete: () => {
        my.hideLoading();
      },
    });
  },
  // 预授权支付
  preAuthorization(data) {
    const { orderStr } = this.data
    my.tradePay({
      orderStr,
      success: (res) => {
        let { resultCode } = res
        if (resultCode === '9000') {
          this.orderSuccess(data)
        } else {
          this.orderList('click');
        }
      },
      fail: () => {
        my.alert({
          title: '提示',
          content: '系统异常请联系客服处理',
          buttonText: '联系客服',
          success: () => {
            this.setData({
              kefuisShow: true,
            });
          }
        })
      },
      complete: () => {
        my.hideLoading(); //加载结束
      }
    });
  },
  //人脸识别认证
  authentication(order_id, resetData) {
    let { testUrl, user_id: zm_user_id } = getApp().globalData;
    my.request({
      url: `${testUrl}/api/user/userFaceAuth`,
      method: 'POST',
      data: {
        zm_user_id,
        order_id,
      },
      dataType: 'json',
      success: (res) => {
        const { code, data: {
          certify_url: url, 
          certify_id: certifyId
        } } = res.data
        if (code === 1) {
          my.startAPVerify({
            url,
            certifyId,
            success: (res) => {
              if (res.resultStatus === '9000') {
                my.request({
                  url: `${testUrl}/api/user/userFaceAuthSuccess`,
                  method: 'POST',
                  data: {
                    order_id
                  },
                  dataType: 'json',
                  success: () => {
                    this.preAuthorization(resetData)
                  },
                  fail: () => { // 成功和失败都拉起预授权
                    this.preAuthorization(resetData)
                  }
                })

              } else {
                // my.showToast({
                //   content: res.resultStatus === '6001' ?
                //     '请先完成人脸识别' :
                //     '人脸识别失败！',
                // });
                this.setData({
                  isHidePlaceOrderPopup: true
                })
                this.orderList('click');
              }
            },
            fail: () => {
              my.alert({
                title: '提示',
                content: '系统异常请联系客服处理',
                buttonText: '联系客服',
                success: () => {
                  this.setData({
                    kefuisShow: true,
                  });
                }
              })
            }
          });
        } else {
          my.hideLoading();
          my.showToast({
            content: res.data.msg
          })
        }
      },
      fail: () => {
        this.orderList('click');
      },
      complete: () => {
        my.hideLoading(); //加载结束
      },
    });
  },

  withhold(_str, callback) {
    //商户代扣
    let vm = this;
    if (my.canIUse('paySignCenter')) {
      my.paySignCenter({
        signStr: _str,
        success: (res) => {
          //console.log("代扣返回参数",res)
          if (res.resultStatus == '7000') {
            //协议签约成功
            let _agreement_no = res.result && JSON.parse(res.result)
              .alipay_user_agreement_page_sign_response.agreement_no;
            callback({
              agreement_no: _agreement_no,
            });
          } else {
            my.hideLoading();
            vm.orderList('click');
            callback(false);
          }
        },
      });
    } else {
      my.hideLoading();
    }
  },
  // isUseAuth(submitParam, _data) {
  //   my.getStorage({
  //     key: 'firstFaceauth',
  //     success: (res) => {
  //       /** 2023.5.19 必须调用人脸识别 */
  //       if (res.data && false) {
  //         //第一次进行人脸识别
  //         this.orderSuccess(_data, function () {
  //           //调用订单状态同步接口
  //         });
  //       } else {
  //         this.authentication(submitParam, _data); //调用人脸识别
  //       }
  //     },
  //     fail: () => {
  //       this.authentication(submitParam, _data); //调用人脸识别
  //     },
  //   });
  // },


  // 下单成功
  orderSuccess(_data) {
    //订单结果
    my.request({
      url: app.globalData.testUrl + '/Api/order/OrderSuccess',
      method: 'POST',
      data: _data,
      dataType: 'json',
      success:  (res) => {
        if (res.data.status == '1001') {
          my.showToast({
            type: 'none',
            content: '支付成功~',
            duration: 1000,
            success: () => {
              my.hideLoading();
              this.orderList('click');
            },
          });
        } else {
          my.showToast({
            type: 'none',
            content: '系统繁忙请重试~',
            duration: 1000
          });
        }
      },
      complete:  () => {
        my.hideLoading();
      },
    });
  },
});